//
//  ComposeViewController.swift
//  MyWeibo
//
//  Created by cat on 15/8/4.
//  Copyright © 2015年 cat. All rights reserved.
//

import UIKit

class ComposeViewController: UIViewController {

    // 键盘输入视图
    private lazy var emoticonVC: EmoticonViewController = EmoticonViewController { [weak self] (emoticon) -> () in
        
        self?.textView.insertEmoticon(emoticon)
        
    }
    
    // MARK: - 监听方法
    func close() {
        
        textView.resignFirstResponder()
        dismissViewControllerAnimated(true, completion: nil)
        
    }
    
    /// 发微博
    func sendStatus() {
        
        print("faweibo")
    }
    
    func inputEmoticon() {
        
//        removekeyboardOberserver()
        
        textView.resignFirstResponder()
        
        textView.inputView = (textView.inputView == nil) ? emoticonVC.view : nil
        
//        addkeyboardOberserver()
        
        textView.becomeFirstResponder()
        
        print("xuanzhebiaoqing")
    }
    
    
    
    
    
    /// 添加键盘通知
    private func addkeyboardOberserver() {
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardChanged:", name: UIKeyboardWillChangeFrameNotification, object: nil)
    }
    
    private func removekeyboardOberserver() {
        
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    /// toolbar底部约束
    private var toolbarBottomCons: NSLayoutConstraint?
    // 键盘变化监听方法
    func keyboardChanged(n: NSNotification) {
        
        let curve = n.userInfo![UIKeyboardAnimationCurveUserInfoKey]!.integerValue
        
        let rect = n.userInfo![UIKeyboardFrameEndUserInfoKey]!.CGRectValue
        let duration = n.userInfo![UIKeyboardAnimationDurationUserInfoKey]!.doubleValue
        
        toolbarBottomCons?.constant = -(UIScreen.mainScreen().bounds.height - rect.origin.y)
        
        UIView.animateWithDuration(duration) {
            
            UIView.setAnimationCurve(UIViewAnimationCurve(rawValue: curve)!)
            
            self.view.layoutIfNeeded()
        }
        
    }
    
    
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        
        
        // 激活键盘
        textView.becomeFirstResponder()
        
        
    }
    
    // MARK: - 搭建界面
    override func loadView() {
        view = UIView()
        
        view.backgroundColor = UIColor.whiteColor()
        preparNav()
        prepareToolbar()
        prepareTextView()
    }
    
    // MARK: - 键盘监听方法
    override func viewDidLoad() {
        super.viewDidLoad()
        
        addkeyboardOberserver()
        
    }

    deinit {
        removekeyboardOberserver()
    }
    
    
    /// 准备导航栏
    private func preparNav() {
        
        // 左右按钮
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: UIBarButtonItemStyle.Plain, target: self, action: "sendStatus")
        navigationItem.rightBarButtonItem?.enabled = false
        
        // 标题栏
        let titleView = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 32))
        let titleLabel = UILabel(color: UIColor.darkGrayColor(), fontSize: 15)
        titleLabel.text = "发微博"
        titleLabel.sizeToFit()
        titleView.addSubview(titleLabel)
        titleLabel.ff_AlignInner(type: ff_AlignType.TopCenter, referView: titleView, size: nil)
        
        let nameLabel = UILabel(color: UIColor.lightGrayColor(), fontSize: 13)
        nameLabel.text = UserAccount.sharedAccount?.name ?? ""
        nameLabel.sizeToFit()
        titleView.addSubview(nameLabel)
        nameLabel.ff_AlignInner(type: ff_AlignType.BottomCenter, referView: titleView, size: nil)
        
        navigationItem.titleView = titleView
    }
    
    
    
    /// 准备文本框
    private func prepareTextView() {
        view.addSubview(textView)
        
        textView.backgroundColor = UIColor.whiteColor()
        
        print(automaticallyAdjustsScrollViewInsets)
        
        textView.contentInset = UIEdgeInsets(top: 64, left: 0, bottom: 0, right: 0)
        
        textView.ff_AlignInner(type: ff_AlignType.TopLeft, referView: view, size: nil)
        textView.ff_AlignVertical(type: ff_AlignType.TopRight, referView: toolbar, size: nil)
        
        // 添加占位符
        placeholderLabel.text = "分享新鲜事..."
        placeholderLabel.sizeToFit()
        textView.addSubview(placeholderLabel)
        placeholderLabel.ff_AlignInner(type: ff_AlignType.TopLeft, referView: textView, size: nil, offset: CGPoint(x: 5, y: 8))
    }
    
    /// 准备 toolbar
    private func prepareToolbar() {
        toolbar.backgroundColor = UIColor(white: 0.8, alpha: 1.0)
        view.addSubview(toolbar)
        
        
         let cons = toolbar.ff_AlignInner(type: ff_AlignType.BottomLeft, referView: view, size: CGSize(width: UIScreen.mainScreen().bounds.width, height: 44))
        // 记录底部约束
        toolbarBottomCons = toolbar.ff_Constraint(cons, attribute: NSLayoutAttribute.Bottom)
        
        // 定义一个数组
        let itemSettings = [["imageName": "compose_toolbar_picture"],
            ["imageName": "compose_mentionbutton_background"],
            ["imageName": "compose_trendbutton_background"],
            ["imageName": "compose_emoticonbutton_background", "action": "inputEmoticon"],
            ["imageName": "compose_addbutton_background"]]
        
        var items = [UIBarButtonItem]()
        for dict in itemSettings {
            items.append(UIBarButtonItem(imageName: dict["imageName"]!, target: self, action: dict["action"]))
            
            // 追加弹簧
            items.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil))
        }
        items.removeLast()
        toolbar.items = items
        
    }
    
    
    // MARK: - 懒加载
    private lazy var textView: UITextView = {
       let tv = UITextView()
        tv.font = UIFont.systemFontOfSize(18)
        
        // 允许垂直拖拽
        tv.alwaysBounceVertical = true
        // 拖拽关闭键盘
        tv.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag
        
        return tv
        
    }()
    
    /// 占位符
    private lazy var placeholderLabel = UILabel(color: UIColor.grayColor(), fontSize: 18)
    
    /// 工具栏
    private lazy var toolbar = UIToolbar()
    
}
